import os
import requests
from bs4 import BeautifulSoup

folder = 'images/'


def count_files(dir_path):
    return len([f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))])


url = 'https://www.kukuc.co/comic/chapter/fuliyuan-nananana/0_33.html'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

img_tags = soup.find_all('img')

# 在当前目录下创建一个名为"images"的文件夹来存放下载的图片  _2  
if not os.path.exists('images'):
    os.makedirs('images')


if count_files(folder) > 1:
    index = count_files(folder)  # 有个时候需要自定义图片开始下标
else:
    index = 0

# 遍历所有图片标签，并下载图片
for idx, img_tag in enumerate(img_tags):
    img_url = img_tag.get('src')

    # 跳过空链接
    if not img_url:
        continue

    # 如果链接不完整，可能需要添加主机名
    if not img_url.startswith('http'):
        img_url = 'https://www.kukuc.co/' + img_url

    # 下载图片并保存到本地
    response = requests.get(img_url)
    img_data = response.content
    img_name = f'images/image{index}.jpg'

    with open(img_name, 'wb') as f:
        f.write(img_data)

    print(f'图片 {img_name} 下载完成')
    index += 1

print("所有图片下载完成！")

print('图片总数:', count_files(folder))
